﻿#region Usings

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

#endregion

namespace KanbanBoard.Client.View.DragAndDrop {
    internal static class DragAndDropHelper {
        public static object GetDataContext(this object obj) {
            if (obj == null) return null;
            return ((FrameworkElement) obj).DataContext;
        }

        public static ItemsControl GetItemsControl(this object control) {
            for (var c = (DependencyObject) control; c != null; c = VisualTreeHelper.GetParent(c)) {
                if (c is ItemsControl) return (ItemsControl) c;
            }
            return null;
        }

        public static UIElement GetItemControl(this object control) {
            for (var c = (DependencyObject) control; c != null; c = VisualTreeHelper.GetParent(c)) {
                if (c is ContentPresenter) return (UIElement) c;
            }
            return null;
        }

        public static ItemsControl GetItemsControl(this MouseEventArgs e) {
            var position = e.GetPosition(Application.Current.RootVisual);
            var elements = VisualTreeHelper.FindElementsInHostCoordinates(position, Application.Current.RootVisual);
            return elements.OfType<ItemsControl>().FirstOrDefault();
        }

        public static UIElement GetItemControl(this MouseEventArgs e) {
            var position = e.GetPosition(Application.Current.RootVisual);
            var elements = VisualTreeHelper.FindElementsInHostCoordinates(position, Application.Current.RootVisual);
            return elements.OfType<ContentPresenter>().FirstOrDefault();
        }

        public static object GetItemOfType(this MouseEventArgs e, Type type) {
            var control = e.GetItemControl();
            var dataContext = control.GetDataContext();
            return type.IsInstanceOfType(dataContext) ? dataContext : null;
        }
    }
}